package com.tbit.uqbike.client.handler.borrowbikehandler;

import com.tbit.common.utils.TraceUtil;
import com.tbit.uqbike.client.common.ResultMsg;
import com.tbit.uqbike.client.constant.RedisConstant;
import com.tbit.uqbike.client.dao.core.BorrowCheckConfigLogDao;
import com.tbit.uqbike.client.pojo.AccountConfig;
import com.tbit.uqbike.client.pojo.Machine;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.pojo.borrowbike.BorrowCheckConfigLog;
import com.tbit.uqbike.client.service.AccountConfigService;
import com.tbit.uqbike.client.service.MachineService;
import com.tbit.uqbike.client.service.RedisService;
import com.tbit.uqbike.client.vo.borrow.BorrowBikeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author lh2
 * @ClassName: FaceRecognitionCheckHandler
 * @Description: 人脸识别校验处理器 ： 首次人脸识别和二次人脸识别校验
 * @date 2023-07-27 11:55:29
 */
@Slf4j
@Component
public class FaceRecognitionCheckHandler extends AbstractCheckHandler {
    @Autowired
    private RedisService redisService;
    @Autowired
    private AccountConfigService accountConfigService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private BorrowCheckConfigLogDao borrowCheckConfigLogMapper;

    @Override
    public ResultMsg handle(BorrowBikeVO vo, String serialNO) {
        log.info("【人脸识别校验处理器】校验开始...");
        // 降级：如果配置了降级，则跳过此处理器，执行下一个处理器
        if (super.getConfig().getDown() == 1) {
            log.info("【人脸识别校验处理器】被降级，已自动跳过！");
            return super.next(vo, serialNO);
        }

        User user = vo.getUser();
        Machine machine = machineService.getByUserCode(vo.getUserCode());
        AccountConfig accountConfig = accountConfigService.getByAccountId(machine.getAccountId());
        /** 区域开启人脸认证 */
        if (accountConfig != null && accountConfig.getFaceCheck() != null && accountConfig.getFaceCheck() == 1) {
            String tmp = redisService.get(RedisConstant.REDIS_USER_FACE + user.getUserId());
            if (tmp == null) {
                return ResultMsg.fail(-30007, "请先人脸认证后在用车", TraceUtil.getTraceIdByLocal());
            }
        }

        log.info("【人脸识别校验处理器】校验通过！");
        BorrowCheckConfigLog bccLog = borrowCheckConfigLogMapper.findByNameAndSerialNO(
                this.getConfig().getHandlerName(), serialNO);
        if (bccLog != null) {
            bccLog.setExecuteResult(1);
            borrowCheckConfigLogMapper.updateByPrimaryKeySelective(bccLog);
        }
        // 执行下一个处理器
        return super.next(vo, serialNO);
    }

}
